/**
 * 从配置活缓存中获取配置
 */
package aorey.database;



import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import aorey.config.FrameworkConfig;
import aorey.database.config.DataConfigTransAction;
import aorey.database.config.DataConfigTransactionSQL;
import aorey.nosql.EhcacheUtil;

public class DataTransactionConfigInfo {

	protected HttpServletRequest request;
	protected EhcacheUtil framework;
	public DataTransactionConfigInfo(HttpServletRequest request)
	{
		this.request =request;
		this.framework = (EhcacheUtil) request.getServletContext().getAttribute("aorey");
	}
	
	public DataConfigTransAction getTransaction(String id) throws DocumentException
	{
		
		DataConfigTransAction dataConfigTransaction = (DataConfigTransAction) this.framework.get("transaction",id);
		if (dataConfigTransaction!=null) {
			return dataConfigTransaction;
		}
		dataConfigTransaction = new DataConfigTransAction();
		StringBuilder stringBuilder = new StringBuilder();
		stringBuilder.append(this.request.getRealPath(""));
		stringBuilder.append(FrameworkConfig.transActionConfig);
		stringBuilder.append("/");
		stringBuilder.append(id);
		stringBuilder.append(".xml");
		String config = stringBuilder.toString();
//		System.out.println(config);
		SAXReader reader = new SAXReader();
        Document document = reader.read(config);
        Element root = document.getRootElement();
        dataConfigTransaction.pid = root.attributeValue("pid");
        dataConfigTransaction.dataSource = root.attributeValue("data_source");
        List<Element> sqlNode = root.elements();
        int sqlNodeSize = sqlNode.size();
        dataConfigTransaction.sqls = new ArrayList<>();
        DataConfigTransactionSQL sql ;
        for(int i = 0;i<sqlNodeSize;i++)
        {
        	sql = new DataConfigTransactionSQL();
        	sql.to = sqlNode.get(i).attributeValue("to");
        	sql.from = sqlNode.get(i).attributeValue("from");
        	sql.sql = sqlNode.get(i).getTextTrim();
        	dataConfigTransaction.sqls.add(sql);
        }
        // 写入公共缓存配置
        this.framework.put("transaction", id, dataConfigTransaction);
		return dataConfigTransaction;
	}
}
